<template>
  <div v-if="element && element.key" :class="{'is-card-table': element.options.isCard}" class="sub-table">
    <div class="top">
      <div style="flex-shrink: 0;"><Title :element="element" isTable /></div>
      <div v-if="element.options.required" class="is-required">*</div>
      <div v-if="element.options && element.options.tip" class="tip">{{ element.options.tip }}</div>
      <div class="flex"/>
      <template v-if="!element.options.hideOperation && !element.options.isCard">
        <PlainCreateBtn>添加</PlainCreateBtn>
        <el-button size="small" class="delete-btn">删除</el-button>
      </template>
    </div>
    <div v-if="element.options && element.options.statistics && statistics && statistics.length" class="statistics-list">
      <dataDisplay
        :data-list="statistics"
        type="row"
        style="width:100%;"/>
    </div>
    <div class="box">
      <div :class="{'empty-container':element.subform.length===0, 'is-card': element.options.isCard }" class="subtable-container scroll">
        <div v-if="!element.options.isCard && !element.options.hideOperation" class="col-item col-num-item">
          <div class="title center"><el-checkbox v-model="checked" class="no-label"><span/></el-checkbox></div>
          <div class="value center"><el-checkbox v-model="checked" class="no-label"><span/></el-checkbox></div>
        </div>
        <div v-if="!element.options.isCard && element.subform.length && !element.options.hideOperation" class="col-item col-num-item">
          <div class="title">序号</div>
          <div class="value center">1</div>
        </div>
        <div v-if="element.options.isCard && element.subform.length" class="card-table-top">
          <div class="card-index">序号1</div>
          <template v-if="!element.options.hideOperation">
            <div class="button-text">复制</div>
            <div class="separate">|</div>
            <div class="button-text">删除</div>
          </template>
        </div>
        <draggable
          v-model="element.subform"
          v-bind="{ group: 'formMake', ghostClass: 'ghost', animation: 200, handle: '.drag-widget' }"
          :move="handelMove"
          :class="{'widget-subtable-container': !element.options.isCard, 'widget-card-subtable': element.options.isCard}"
          class="widget-subtable"
          item-key="name"
          filter="col-item-empty"
          @change="handleWidgetChange($event, element)"
          @add="handleWidgetColAdd($event, element)"
        >
          <template v-if="!element.options.isCard">
            <div v-for="(col, index) in element.subform" :key="col.key" :class="{active: selectWidget && col.key === selectWidget.key, 'width200': col.type === 'upAttachment'}" class="col-item drag-widget" @click.stop="setSelect(col)">
              <div class="title">
                <span v-if="col.options && col.options.required" class="required">*</span>
                <div class="ellipsisOne">{{ col.name }}</div>
                <ToolTip v-if="col.options && col.options.tip" :icon="tipIcon" :content="col.options.tip" class="ml5" />
              </div>
              <div :style="col.options.readonly?{padding: '0 8px'}:''" class="value">
                <FormMakeElement :element="col" :style="{ width: col.options.width + 'px' }" is-pre-view is-table @handleFormUserSelect="handleFormUserSelect" />
                <div class="form-mask"/>
              </div>
              <div v-if="selectWidget && col.key === selectWidget.key" class="tool">
                <!-- <div class="icon drag-widget"><i class="el-icon-rank font13" /></div> -->
                <img :src="copyIcon" class="icon" alt="复制" @click.stop="handleWidgetClone(col, index)">
                <img :src="deleteIcon" class="icon" alt="删除" @click.stop="handleWidgetDelete(index)">
              </div>
            </div>
            <div slot="footer" class="col-item-empty">从左侧拖拽添加字段</div>
          </template>
          <template v-else-if="element.subform.length">
            <TableCardView
              v-for="(col, index) in element.subform"
              :key="col.key"
              :element="col"
              class="card-element-list drag-widget"
              is-pre-view
              @handleWidgetClone="handleWidgetClone($event, index)"
              @handleWidgetDelete="handleWidgetDelete(index)" />
          </template>
          <div v-else class="col-item-empty">从左侧拖拽添加字段</div>
        </draggable>
        <div v-if="element.options.isCard && element.subform.length && !element.options.hideOperation" class="card-table-tool">
          <PlainCreateBtn>添加</PlainCreateBtn>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/**
 * 子表单 - 只用作预览
 */
import { mapState } from 'vuex';
import Title from './Title';
import draggable from 'vuedraggable';
import tipIcon from '@/assets/process/tip.png';
import incomeAmount from '@/assets/dataDisplay/icon_45.png';
import FormMakeElement from './FormMakeElement';
import TableCardView from './Subtable/tableCardView';
import dataDisplay from '@/components/Common/baseComponent/dataDisplay';
import { EventBus } from '@/utils/eventBus';
import { isNumberType } from '@/utils/formMakeUtils.js';
import LimitMove from '@/views/legal/process/components/formMake/components/mixins/limitMove';
import copyIcon from '@/assets/auditProcess/copy_form.png';
import deleteIcon from '@/assets/auditProcess/delete_form.png';

export default {
  name: 'SubTableView',
  components: { Title, draggable, FormMakeElement, dataDisplay, TableCardView },
  mixins: [LimitMove],
  model: {
    prop: 'value',
    event: 'changeData'
  },
  props: {
    value: {
      type: Array,
      default: null
    },
    element: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      tipIcon, incomeAmount,
      checked: false,
      copyIcon, deleteIcon
    };
  },
  computed: {
    ...mapState({
      'selectWidget': state => state.formMake.selectWidget
    }),
    statistics() {
      const statistics = this.element.options.statistics;
      if (!statistics || statistics.length === 0) return null;
      const keys = [];
      statistics.forEach(i => {
        const item = this.element.subform.find(j => j.key === i);
        if (item) keys.push({ data: null, label: `${item.name}：`, icon: incomeAmount });
      });
      return keys;
    }
  },
  watch: {
    'element.options.statistics': {
      handler(newVal, oldVal) {
        const n1 = newVal.length;
        const n2 = oldVal.length;
        let type = n1 > n2 ? 'add' : 'remove';
        if (n1 === 0) type = 'clear';
        let changeStatistics = '';
        if (type === 'add') {
          const item = newVal.find(i => {
            return !oldVal.includes(i);
          });
          changeStatistics = item;
        } else if (type === 'remove') {
          const item = oldVal.find(i => {
            return !newVal.includes(i);
          });
          changeStatistics = item;
        } else {
          changeStatistics = oldVal;
        }
        EventBus.$emit('formOptionsChange', { type: `${type}Statistics`, changeStatistics, data: _.cloneDeep(this.selectWidget) });
      },
      deep: true
    }
  },
  methods: {
    changeData() {
      this.$emit('changeData', this.value);
    },
    handleWidgetClone(element, index) {
      const cloneElement = _.cloneDeep(element);
      const key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      cloneElement.key = key;
      cloneElement._isNew = true;
      this.element.subform.splice(index, 0, cloneElement);
      this.$store.dispatch('setSelectWidget', cloneElement);
      EventBus.$emit('formOptionsChange', { type: 'subtable-add', data: _.cloneDeep(cloneElement) });
    },
    handleWidgetDelete(index) {
      const deleteItem = this.element.subform[index];
      if (isNumberType(deleteItem) && this.element.options.statistics && this.element.options.statistics.length) {
        this.element.options.statistics = this.element.options.statistics.filter(i => {
          return i !== deleteItem.key;
        });
      }
      EventBus.$emit('formOptionsChange', { type: 'subtable-remove', data: _.cloneDeep(deleteItem) });
      this.element.subform.splice(index, 1);
      if (this.element.subform.length > 0) {
        this.$store.dispatch('setSelectWidget', this.element.subform[0]);
      } else {
        this.$store.dispatch('setSelectWidget', this.element);
      }
    },
    setSelect(element) {
      this.$store.dispatch('setSelectWidget', element);
    },
    handleFormUserSelect(data) {
      this.$emit('handleFormUserSelect', data);
    },
    // 添加组件事件
    handleWidgetChange(e, col) {
      if (e.removed) {
        EventBus.$emit('formOptionsChange', {
          type: 'subtable-remove',
          isKeyNotChange: true,
          data: _.cloneDeep(e.removed.element)
        });
        const deleteItem = e.removed.element;
        if (isNumberType(deleteItem) && this.element.options.statistics && this.element.options.statistics.length) {
          this.element.options.statistics = this.element.options.statistics.filter(i => {
            return i !== deleteItem.key;
          });
        }
      }
    },
    handleWidgetColAdd(e, col) {
      let newIndex = e.newIndex;
      if (!newIndex && newIndex !== 0) return;
      if (newIndex >= col.subform.length) {
        newIndex--;
      }
      // 从栅格或者中部移动过来的，说明是栅格或者中部中删除，需要出发删除事件
      const isFromMidOrGrid = e.from.className.indexOf('widget-grid-list') >= 0 || e.from.className.indexOf('widget-list') >= 0;
      if (isFromMidOrGrid) {
        const deleteItem = _.cloneDeep(col.subform[newIndex]);
        EventBus.$emit('formOptionsChange', { type: 'remove', isKeyNotChange: true, data: deleteItem });
      }
      const widgetItem = this.extendsProps(col.subform[newIndex]);
      widgetItem.subformName = col.name;
      col.subform[newIndex] = widgetItem;
      this.$store.dispatch('setSelectWidget', widgetItem);
      // 当职位组件从外部移入子表单，需要重置跟随人员字段
      if (widgetItem.type === 'post' && widgetItem.options.follower) {
        widgetItem.options.follower = null;
      }
      this.$forceUpdate();
      EventBus.$emit('formOptionsChange', { type: 'subtable-add', isKeyNotChange: isFromMidOrGrid, data: _.cloneDeep(widgetItem) });
    },
    extendsProps(item) {
      // 为拖拽到容器的元素添加唯一 key
      const key = new Date().valueOf() + '_' + Math.ceil(Math.random() * 99999);
      const cloneItem = _.cloneDeep(item);
      // 给新添加进来的组件，添加新的属性，但是为了不影响原数据，所以深拷贝
      if (!cloneItem.key) {
        cloneItem.key = key;
        cloneItem._isNew = true;
      }
      cloneItem.isSubTable = true;
      cloneItem.linkFormKey = this.element.key;
      return cloneItem;
    },
    cloneDeep(data) {
      return _.cloneDeep(data);
    }
  }
};
</script>

<style lang="scss" scoped>
@import './mixins/style.scss';
.sub-table {
  padding: 0 12px;
  .top {
    margin-bottom: 12px;
    display: flex;
    align-items: center;
  }
  .tip {
    color: #999;
    font-size: 12px;
    margin-left: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }
  .flex {
    flex:1;
  }
  &.is-card-table {
    padding: 0;
    .card-element-list {
      width: 100%;
    }
    .top {
      padding: 0 12px;
      margin-bottom: 6px;
    }
  }
  &::v-deep {
    .el-scrollbar__bar.is-horizontal {
      z-index: 3;
    }
    .defaultWidth {
      width: 100%;
    }
    .subtable-container:not(.is-card) {
      display: flex;
      border: 1px solid #ebeefd;
      border-radius: 2px;
      .el-input__inner,.user-select-input,.formula-input-inner {
        height: 56px;
        border-radius: 0;
        border-color: transparent !important;
        width: 100%;
        background: #fff !important;
      }
      .formula-input-inner {
        line-height: 56px;
      }
      .formula-input-container {
        width: 100%;
      }
      .threee-level-area-wrap {
        .el-select {
          width: 100%;
        }
      }
      .el-textarea__inner {
        border-color: transparent;
        background: #fff !important;
      }
    }
  }
}
.ml5 { margin-left: 5px;}

.subtable-container {
  position: relative;
  background-color: #fff;
  &.empty-container {
    border: 1px dashed #dddddd;
    border-radius: 4px;
    .col-item-empty {
      width: 290px;
    }
    .col-num-item {
      border-right: 1px dashed #dddddd;
    }
    .col-num-item .title{
      background-color: #fff;
    }
  }
  &.is-card {
    width: 100%;
    border: none;
    .widget-card-subtable {
      width: 100%;
    }
    .col-item-empty {
      width: 100%;
      height: 96px;
    }
  }
}
.box {
  display: flex;

}
.widget-subtable-container {
  display: flex;
  min-height: 96px;
  // width: 100%;
}
.required {
  color: #F56C6C;
}
.center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.statistics-list {margin-bottom: 12px;}
.col-item {
  max-width: 100%;
  flex-shrink: 0;
  border: 1px dashed transparent;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
  min-width: 120px;
  position: relative;
  &:last-child {
    border-right: 1px solid transparent;
  }
  &.col-num-item {
    flex-shrink: 0;
    border-right: 1px solid #ebeef5;
    display: flex;
    flex-direction: column;
    width: 50px;
    min-width: auto;
  }
  &.active {
    border: 1px solid #406eff;
  }
  .title {
    background-color: #f8f8f9;
    line-height: 34px;
    overflow: hidden;
    text-overflow: ellipsis;
    min-height: 41px;
    white-space: nowrap;
    padding: 3px 10px;
    font-weight: 550;
    color: #141c3d;
    font-size: 14px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ebeef5;
  }
  .value {
    background-color: #fff;
    // padding: 0px 5px;
    font-size: 14px;
    color: #333;
    flex: 1;
    position: relative;
    &::v-deep {
      .pdr {
        padding-right: 0;
      }
      .defaultWidth {
        width: 100%;
      }
    }
  }
  .form-mask {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
    height: 100%;
    width: 100%;
  }
}
.col-item-empty {
  font-size: 14px;
  color: #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0 17px;
  flex-shrink: 0;
}
.col-item-tip {
  display: flex;
  align-items: center;
  background-color: #fff;
  flex-shrink: 0;
  min-height: 100%;
  font-size: 14px;
  color: #ddd;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
// .width200 {
//   // width: 200px;
// }
.tool {
  position: absolute;
  right: 6px;
  bottom: 6px;
  z-index: 10;

  display: flex;
  .icon {
    margin-left: 6px;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    background: #fff;
  }
  .drag-widget {
    cursor: move !important;
  }
}
.delete-btn {
  color: #666666;
  border-color: #ddd;
  background-color: #fff;
  padding: 7px 8px;
}
.no-label {
  &::v-deep {
    .el-checkbox__label {
      display: none !important;
    }
  }
}
.scroll {
  @include scrollBar($x: auto, $y: hidden);
}
.is-required {
  color: #F56C6C;
  margin-left: 3px;
}

.card-table-top {
  display: flex;
  align-items: center;
  padding: 0 9px;
  height: 40px;
  background-color: #f9f9f9;
  margin: 6px 12px 6px 12px;
  .card-index {
    font-size: 14px;
    flex: 1;
    color: #141C3D;
    font-weight: 550;
  }
  .separate {
    margin: 0 5px;
    color: #ddd;
  }
}
.card-table-tool {
  margin: 5px 0 5px 12px;
}
</style>
